﻿using System;
using System.Data.Linq;
using System.Linq;
using System.Linq.Expressions;

namespace Recursos.Model
{
    public class Repository<T> : IRepository<T> where T : class, IEntity
    {
        protected Table<T> DataTable;

        public Repository(DataContext dataContext)
        {
            DataTable = dataContext.GetTable<T>();
        }

        #region IRepository<T> Members

        public int Insert(T entity)
        {
            try
            {
                DataTable.InsertOnSubmit(entity);
                return 1;
            }
            catch(Exception ex)
            {
                return 0;
            }

        }

        public void Delete(int id)
        {
            var deleted = DataTable.Single(e => e.id.Equals(id));
            deleted.Borrado = true;
        }

        public IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate)
        {
            return DataTable.Where(predicate).Where(row=>row.Borrado==false);
        }
        public T SearchOne(Expression<Func<T, bool>> predicate)
        {
            try
            {
                return DataTable.Single(predicate);
            }
            catch (Exception)
            {
                return null;
            }

        }

        public IQueryable<T> GetAll()
        {
            return DataTable.Where(row => row.Borrado.Equals(false)).OrderBy(x => x.id);
        }

        public IQueryable<T> GetErased()
        {
            return DataTable.Where(row => row.Borrado.Equals(true));
        }

        public T GetById(int id)
        {
            // Beware the == operator throws NotSupported Exception!
            // 'The Mapping of Interface Member is not supported'
            // Use .Equals() instead
            return DataTable.Single(e => e.id.Equals(id));
        }

        #endregion
    }
}